package com.unitd.frame.springweb.upload.multipart.stream;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import java.io.IOException;

/**
 * @desc servlet请求的输入流的限制流处理
 * @filename LimitedServletInputStream.java
 * @copyright www.unitd.com
 * @author Hudan
 * @version 1.0
 * @date 2017/4/10
 */
public class LimitedServletInputStream extends ServletInputStream {
	private ServletInputStream in;
	private int totalExpected;
	private int totalRead = 0;

	public LimitedServletInputStream(ServletInputStream in, int totalExpected) {
		this.in = in;
		this.totalExpected = totalExpected;
	}

	@Override
	public int readLine(byte[] b, int off, int len) throws IOException {
		int left = this.totalExpected - this.totalRead;
		if (left <= 0) {
			return -1;
		} else {
			int result = this.in.readLine(b, off, Math.min(left, len));
			if (result > 0) {
				this.totalRead += result;
			}

			return result;
		}
	}

	@Override
	public boolean isFinished() {
		return false;
	}

	@Override
	public boolean isReady() {
		return false;
	}

	@Override
	public void setReadListener(ReadListener readListener) {

	}

	@Override
	public int read() throws IOException {
		if (this.totalRead >= this.totalExpected) {
			return -1;
		} else {
			int result = this.in.read();
			if (result != -1) {
				++this.totalRead;
			}

			return result;
		}
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		int left = this.totalExpected - this.totalRead;
		if (left <= 0) {
			return -1;
		} else {
			int result = this.in.read(b, off, Math.min(left, len));
			if (result > 0) {
				this.totalRead += result;
			}

			return result;
		}
	}
}